<template>
  <div class="search">
    <!-- 搜索栏 -->
    <form action="/" class="search_form">
      <van-search
        v-model="searchValue"
        show-action
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="isShowResult=false"
        @focus="isShowResult=false"
      />
    </form>
    <!-- 搜索结果 -->
    <search-results
      :search-text="searchValue"
      v-if="isShowResult"/>
    <!-- 搜索历史 -->
    <search-history
      :history="history"
      @search="onSearch"
      @clear-history="history= []"
      v-else-if="!searchValue" />
    <!-- 搜索联想建议 -->
    <search-suggestion
      :search-text="searchValue"
      @search="onSearch"
      v-else/>
  </div>
</template>

<script>
import searchHistory from './components/searchHistory'
import searchResults from './components/searchResults'
import searchSuggestion from './components/searchSuggestion'
import { setItem, getItem } from '@/utils/storage.js'
export default {
  data () {
    return {
      searchValue: '',
      isShowResult: false,
      // 用来存储搜索历史
      history: getItem('hmtt_history') || []
    }
  },

  components: {
    searchHistory,
    searchResults,
    searchSuggestion
  },

  created () {

  },

  watch: {
    history (nVal) {
      setItem('hmtt_history', nVal)
    }
  },

  methods: {
    // 在手机上点击搜索按钮，敲回车
    onSearch (val) {
      if (val.trim() === '') return this.$toast('请输入搜索内容')
      // 查找搜索历史是否包含当前值
      const index = this.history.indexOf(val)
      // 如果有 先删除
      if (index !== -1) this.history.splice(index, 1)
      // 向前添加搜索历史
      this.history.unshift(val)
      this.isShowResult = true
      this.searchValue = val
    },
    // 点击取消
    onCancel () {
      console.log('取消')
    }
  }
}
</script>

<style scoped lang='less'>
.search {
  padding-top: 108px;
  .van-search {
    background: #3295F9;
  }
  .van-search__action {
    color: #fff;
  }
  .search_form {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 2;
  }
}

</style>
